package com.inputabc.ct.v1.util;

import com.inputabc.ct.v1.setting.KeySetting;
import com.inputabc.ct.v1.setting.SettingContext;

import java.io.*;
import java.util.*;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.Map.Entry;

/**
 * 将翻译api的密钥信息加密读写
 *
 * @author gaoweiyi
 */
public class KeyIOUtils {
    private static KeySetting keySetting = SettingContext.keySetting;
    private static String filePath = PFileUtils.getTargetPath() + "/AppData/Local/ctcatv1/";

    static {

        File dir = new File(filePath);
        if (dir.exists() == false) {
            dir.mkdirs();
            File file = new File(dir, "config");
            try {
                file.createNewFile();
                filePath = file.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if (dir.isFile()) {
                dir.delete();
                dir.mkdirs();
                try {
                    File file = new File(dir, "config");
                    file.createNewFile();
                    filePath = file.getAbsolutePath();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                File file = new File(dir, "config");
                if (file.exists() == false) {
                    try {
                        file.createNewFile();
                        filePath = file.getAbsolutePath();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    filePath = file.getAbsolutePath();
                }
            }
        }

    }

    public static void load() {
        Properties p = new Properties();
        try {
            p.load(new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8")));
            Set<Entry<Object, Object>> entrySet = p.entrySet();
            Map<String, String> keyMap = new HashMap<>();
            for (Entry<Object, Object> entry : entrySet) {
                String key = AES.decryptString((String) entry.getKey(), AES.key);
                String value = AES.decryptString((String) entry.getValue(), AES.key);
                Decoder decoder = Base64.getDecoder();
                byte[] decodedKey = decoder.decode(key);
                byte[] decodedValue = decoder.decode(value);
                keyMap.put(new String(decodedKey, "utf-8")
                        , new String(decodedValue, "utf-8"));
            }
            Set<Entry<String, String>> keyMapEntries = keyMap.entrySet();
            KeySetting.Youdao youdaoKeySetting = keySetting.getYoudao();
            KeySetting.Baidu baiduKeySetting = keySetting.getBaidu();
            for (Entry<String, String> entry : keyMapEntries) {
                if ("youdao.app_key".equals(entry.getKey())) {
                    youdaoKeySetting.setAppKey(entry.getValue());
                } else if ("youdao.app_secret".equals(entry.getKey())) {
                    youdaoKeySetting.setAppSecret(entry.getValue());
                } else if ("baidu.app_id".equals(entry.getKey())) {
                    baiduKeySetting.setAppId(entry.getValue());
                } else if ("baidu.security_key".equals(entry.getKey())) {
                    baiduKeySetting.setSecurityKey(entry.getValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains("For input string")) {
                boolean delete = new File(filePath, "config").delete();
            }
        }
    }

    public static void store() {
        Properties p = new Properties();
        String youdaoAppKey = keySetting.getYoudao().getAppKey();
        String youdaoAppSecret = keySetting.getYoudao().getAppSecret();
        String baiduAppId = keySetting.getBaidu().getAppId();
        String baiduSecurityKey = keySetting.getBaidu().getSecurityKey();
        Encoder encoder = Base64.getEncoder();
        try {
            String key = AES.key;
            p.setProperty(AES.encryptString(new String(encoder.encode("youdao.app_key".getBytes("utf-8")), "utf-8"), key),
                    AES.encryptString(new String(encoder.encode(youdaoAppKey.getBytes("utf-8")), "utf-8"), key));
            p.setProperty(
                    AES.encryptString(new String(encoder.encode("youdao.app_secret".getBytes("utf-8")), "utf-8"), key),
                    AES.encryptString(new String(encoder.encode(youdaoAppSecret.getBytes("utf-8")), "utf-8"), key));
            p.setProperty(AES.encryptString(new String(encoder.encode("baidu.app_id".getBytes("utf-8")), "utf-8"), key),
                    AES.encryptString(new String(encoder.encode(baiduAppId.getBytes("utf-8")), "utf-8"), key));
            p.setProperty(
                    AES.encryptString(new String(encoder.encode("baidu.security_key".getBytes("utf-8")), "utf-8"), key),
                    AES.encryptString(new String(encoder.encode(baiduSecurityKey.getBytes("utf-8")), "utf-8"), key));
            p.store(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "utf-8")), "\\");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
